package cn.com.ali.maxcompute;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTest {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName(Config.DRIVER_NAME);

        try(Connection connection=DriverManager.getConnection(Config.JDBC_URL,Config.ACCESSID,Config.ACCESSKEY);
            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery(Config.SQL.QUERY);
        ) {
            int rowno = 1;
            int columnCount = resultSet.getMetaData().getColumnCount();

            while (resultSet.next()) {
                System.out.println("=========================="+rowno+"==========================");
                for (int i = 1; i < columnCount+1; i++) {
                    System.out.print(resultSet.getMetaData().getColumnName(i) + ":\t" + resultSet.getObject(i) + "\t");
                }
                System.out.println();
            }
        }
    }
    public void test() throws SQLException,ClassNotFoundException {
        try {
            Class.forName(Config.DRIVER_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }

        Connection conn = DriverManager.getConnection(Config.JDBC_URL,Config.ACCESSID,Config.ACCESSKEY);


        // create a table
        Statement stmt = conn.createStatement();
        final String tableName = "jdbc_test";
        stmt.execute("DROP TABLE IF EXISTS " + tableName);
        stmt.execute("CREATE TABLE " + tableName + " (key BIGINT, value STRING)");

        // get meta data
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("product = " + metaData.getDatabaseProductName());
        System.out.println("jdbc version = "
                + metaData.getDriverMajorVersion() + ", "
                + metaData.getDriverMinorVersion());
        ResultSet tables = metaData.getTables(null, null, tableName, null);
        while (tables.next()) {
            String name = tables.getString("TABLE_NAME");
            System.out.println("inspecting table: " + name);
            ResultSet columns = metaData.getColumns(null, null, name, null);
            while (columns.next()) {
                System.out.println(
                        columns.getString("COLUMN_NAME") + "\t" +
                                columns.getString("TYPE_NAME") + "(" +
                                columns.getInt("DATA_TYPE") + ")");
            }
            columns.close();
        }

        tables.close();
        stmt.close();
        conn.close();
    }
}
